import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import {Message} from 'element-ui'
import {getToken} from './utils/auth' // 验权

// 不重定向白名单
const whiteList = ['/login'];

// 路由守卫
router.beforeEach((to, from, next) => {
    //开始进度条
    NProgress.start();
    //请求头中含有token
    if (getToken()) {
        if (to.path === '/login') {
            //重定向首页
            next({path: '/'})
            //结束进度条
            NProgress.done()
        } else {
            //拉取用户信息
            // if (store.state.roles === undefined){
            if (store.getters.roles.length === 0){
                store.dispatch('GetInfo').then(res => {
                    let menus = res.menuList;
                    let username = res.username;
                    // 生成可访问的路由表
                    store.dispatch('GenerateRoutes', { menus, username}).then(() => {
                        // 动态添加可访问路由表
                        router.addRoutes(store.getters.addRouters)
                        next({ ...to, replace: true })
                    }).catch((err) => {
                        store.dispatch('FedLogOut').then(() => {
                            console.log('输入错误信息',err)
                            Message.error(err || 'Verification failed, please login again')
                            next({ path: '/' })
                        })
                    })
                })
            }else {
                next();
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            next("/login");
            NProgress.done();
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})